package org.opendatakit.sensors.wifi;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.DhcpInfo;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;


public class MulticastThread implements Runnable{

public final String TAG = "Multicast Thread";	
	
public static final int DGRAM_LENGTH = 1024;
public static final int PORT = 50000;
//public static final int ODK_PORT = 8092;

static String multicast_group = "225.4.5.6";
static String broadcast_group = "11.0.0.255";
int ttl = 5;

MulticastSocket ms;
DatagramSocket ds;
String message;
String ip;
Context context;
//MulticastService multicast;
public MulticastThread(String cmd,Context c){
	context=c;
	this.message=cmd;
	
	try {
			ms = new MulticastSocket();
			ds = new DatagramSocket();
			ds.setBroadcast(true);
			Log.d("MST", ms.toString());

	} catch (IOException e) {
		e.printStackTrace();
	}
	
	
	
}

InetAddress getBroadcastAddress() throws IOException {
	android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager)context.getSystemService(Context.WIFI_SERVICE);
    DhcpInfo dhcp = wifi.getDhcpInfo();
    // handle null somehow

    int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
    byte[] quads = new byte[4];
    for (int k = 0; k < 4; k++)
      quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
    return InetAddress.getByAddress(quads);
}

@SuppressWarnings("deprecation")
public void run() {

	byte buf[] = new byte[1024];
	DatagramPacket pack;
	buf=message.getBytes();
	long startTime = System.currentTimeMillis();
	long elapsedTime = 0L;

	while (elapsedTime < 5*1000) {
	try {
		pack = new DatagramPacket(buf, buf.length, InetAddress.getByName(multicast_group), PORT);
		ms.send(pack,(byte)ttl);
		buf=message.getBytes();
		pack = new DatagramPacket(buf, buf.length, getBroadcastAddress(), PORT);
		ds.send(pack);
		Log.d("Sent","Sent data to: " + pack.getAddress().toString() + ":" + pack.getPort() + " with length: " +
			    pack.getLength());
	} catch (UnknownHostException e2) {
		// TODO Auto-generated catch block
		e2.printStackTrace();
	}//	
	catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	elapsedTime = (new Date()).getTime() - startTime;
	try {
		Thread.sleep(300);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}
	
	Intent i = new Intent();
	i.setAction(WifiAdapter.ACTION_DISCOVERY_FINISHED);
	LocalBroadcastManager.getInstance(context).sendBroadcastSync(i);
	Log.d(TAG, "Sent Intent Action Discovery Finished");
	}

}